package com.study.talk.ui.app.register.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.study.talk.R
import com.study.talk.ui.app.base.BaseFragment
import com.study.talk.databinding.FragmentSettingPasswordBinding
import com.study.talk.ui.app.register.RegisterViewModel
import com.study.talk.utils.alert.AlertUtil
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class SettingPasswordFragment : BaseFragment() {

    private lateinit var binding: FragmentSettingPasswordBinding

    private val parentViewModel by lazy { ViewModelProvider(requireActivity())[RegisterViewModel::class] }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        binding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_setting_password, container, false)
        binding.vm = parentViewModel
        binding.lifecycleOwner = this
        parentViewModel.complete.observe(viewLifecycleOwner) {
            AlertUtil.showCustomDialog(
                requireActivity(), "注册成功", "你的用户名为${it.username}\n快去登录吧"
            ) {
                if (activity != null) requireActivity().finish()
            }
        }
        parentViewModel.fail.observe(viewLifecycleOwner) {
            AlertUtil.showEnsureAction(
                requireActivity(), "注册失败", it
            ) {
                this.findNavController()
                    .navigate(R.id.action_settingPasswordFragment_to_phoneNumberFragment)
            }
        }
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.registerBtn.setOnClickListener {
            if (parentViewModel.passwordCheck()) {
                parentViewModel.passwordSubmit()
            }
        }
    }
}